<template>
    <view v-show="isEmpty" class="study-course safeArea" @click="pageClick">
        <view>
            <u-navbar
                :is-back="BGpercent"
                :background="{ background: `rgba(255,255,255,${BGpercent})` }"
                :border-bottom="false"
                :immersive="type == 1"
            >
                <view
                    class="w-[400rpx] overflow-hidden whitespace-nowrap text-ellipsis"
                    :style="{ color: `rgba(0,0,0,${BGpercent})` }"
                    style="min-width: 0"
                >
                    {{ activeCourse?.name || courseData?.name }}
                </view>
            </u-navbar>
        </view>
        <!-- Main Start -->
        <!-- 课程信息 -->
        <view class="course relative">
            <!--图文课程顶部显示标题-->
            <view class="course-info bg-white !pt-[100rpx]" v-if="type == 1">
                <!-- 课程名称 -->
                <view class="text-xl font-medium flex-1">{{
                    activeCourse?.name || courseData?.name
                }}</view>
                <!-- 介绍 -->
                <view class="text-muted mt-[18rpx] text-sm">
                    {{ courseDetailInfo.create_time }}
                    {{ courseDetailInfo?.teacher?.name }}
                </view>
            </view>
            <!-- 音频 -->
            <view v-if="type == 2">
                <view class="audio-wrapper" v-if="type == 2 && cateId == courseData.id">
                    <!-- <u-sticky :enable="true" :offset-top="0" :h5-nav-height="0"> -->
                    <view class="py-[20rpx]">
                        <l-audio
                            :src="courseData.content"
                            :cata-id="courseData.id"
                            :course-id="courseData.courseId"
                            :courseDetailInfo="courseDetailInfo"
                            :initial-time="courseData.studyDuration / 1000"
                            @refresh="handleRefresh"
                        ></l-audio>
                    </view>
                    <!-- </u-sticky> -->
                </view>
                <view v-if="isnoBuy" class="flex w-full h-[400rpx] justify-center items-center">
                    <u-button type="primary" @click="backToBuy" shape="circle" class=""
                        >购买课程</u-button
                    >
                </view>
            </view>
            <!-- 视频 -->
            <view class="h-[400rpx] bg-black" v-if="type == 3">
                <view class="video-wrapper" v-if="type == 3 && cateId == courseData.id">
                    <lVideo
                        :src="courseData.content"
                        :initialTime="courseData.studyDuration / 1000"
                        :cata-id="courseData.id"
                        :course-id="courseData.courseId"
                    ></lVideo>
                </view>
                <view v-if="isnoBuy" class="flex w-full h-[400rpx] justify-center items-center">
                    <u-button type="primary" @click="backToBuy" shape="circle" class=""
                        >购买课程</u-button
                    >
                </view>
            </view>
            <view v-if="type == 1">
                <!-- 图文 -->
                <view
                    class="bg-white p-[30rpx] pb-[100rpx]"
                    v-if="type == 1 && cateId == courseData.id"
                >
                    <mp-html :content="courseData.content" />
                </view>
                <view v-if="isnoBuy" class="flex w-full h-[400rpx] justify-center items-center">
                    <u-button type="primary" @click="backToBuy" shape="circle" class=""
                        >购买课程</u-button
                    >
                </view>
            </view>
            <!--图文目录-->
            <view
                class="bottom-0 px-[20rpx] safeArea fixed w-full bg-white"
                :class="{ 'opacity-0': TWcateHide }"
                v-if="type == 1"
            >
                <ITbottom
                    :cate-id="cateId"
                    :course-detail-info="courseDetailInfo"
                    @refresh="handleRefresh"
                ></ITbottom>
            </view>
        </view>

        <!-- 课程目录 -->
        <view class="mt-[30rpx]" v-if="type != 1">
            <tabs
                :current="active"
                fontSize="32"
                height="100"
                bar-width="60"
                inactiveColor="#888888"
                :top="offsetHeight(type)"
                isFixed
                :tabsStyle="{ 'border-bottom': '1px solid #F6F6F6' }"
                :barStyle="{ bottom: '-2rpx' }"
                barHeight="6"
            >
                <tab name="目录" :i="1" :index="active">
                    <view style="min-height: 700rpx">
                        <course-catalogue
                            :list="courseDetailInfo.courseCatalogues"
                            :type="courseDetailInfo.type"
                            :status="courseDetailInfo.purchased"
                            :cateId="cateId"
                            @refresh="refleshThrottle"
                        >
                        </course-catalogue>
                    </view>
                </tab>
            </tabs>
        </view>
        <!-- Main End -->
    </view>

    <!-- empty Start -->
    <view v-show="!isEmpty" class="empty">
        <u-empty
            text="抱歉，该课程不存在~"
            :src="'/static/images/empty/collection.png'"
            :icon-size="300"
            color="#888888"
        >
            <template #bottom>
                <view class="empty-bottom">
                    <u-button
                        @click="goPage('/pages/index/index')"
                        shape="circle"
                        :ripple="true"
                        :hair-line="false"
                        type="primary"
                    >
                        去看看其它</u-button
                    >
                </view>
            </template>
        </u-empty>
    </view>
    <!-- empty End -->
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { onLoad, onPageScroll, onShow } from '@dcloudio/uni-app'
import LAudio from './components/l-audio.vue'
import lVideo from './components/l-video.vue'
import ITbottom from './components/ITbottom.vue'
import CourseCatalogue from '@/components/catalogue/index.vue'
import { useUserStore } from '@/stores/user'
import { apiPlaceOrder } from '@/api/order'
import { apiCourseDetail, apiCourseCatalogue, apiCompletedStudy } from '@/api/goods'
import { objectSort, debounce, throttle } from '@/utils/util'

/** Interface Start **/
interface CourseDataObj {
    id: number // 目录ID
    courseId: number // 课程ID
    name: string // 课程名称
    feeType: number // 是否免费
    cover: string // 封面
    content: string // 内容
    studyDuration: number //已经学习时长
}
/** Interface End **/

/** Data Start **/
const courseData = ref<CourseDataObj>({
    id: 0,
    courseId: 0,
    name: '',
    feeType: 0,
    cover: '',
    content: '',
    studyDuration: 0
})
const courseDetailInfo = ref<any>({
    course_status: 0,
    courseCatalogues: []
})
// 是否已下架
const isEmpty = ref<boolean>(true)
//课程是否未购买
const isnoBuy = ref<boolean>(false)
// 初始化课程详情ID，（在专栏时点击会覆盖原始ID，所以使用原始ID去请求课程详情，防止在支付后跳转回来课程ID不对现象
const initCourseId = ref<number | string>('')
// 课程ID
const courseId = ref<number | string>('')
// 目录ID
const cateId = ref<number | string>('')
//正在播放的目录
const activeCourse: any = ref()
// 课程目录｜｜评价｜｜介绍索引
const active = ref(0)
// 课程类型
const type = ref(0)
//顶部导航栏背景颜色
const BGpercent = ref(0)
//图文目录显示/隐藏
const TWcateHide = ref(false)

/** Data End **/

/** Computed Start **/
/**
 * @description 是否登陆
 */
const userStore = useUserStore()
const isLogin = computed(() => userStore.token)

const offsetHeight = computed(() => {
    return (type: any) => {
        switch (type) {
            case 1:
                return 0
            case 2:
                return 200
            case 3:
                return 400
        }
    }
})
/** Computed End **/

/** Methods Start **/
/**
 * @return { Promise }
 * @description 获取课程详情
 */
const initCourseDetail = async (): Promise<void> => {
    try {
        courseDetailInfo.value = await apiCourseDetail({
            id: initCourseId.value
        })
        //课程目录排序
        courseDetailInfo.value.courseCatalogues = objectSort(
            courseDetailInfo.value.courseCatalogues,
            'sort'
        )
    } catch (err) {
        console.log('获取课程详情=> ', err)
        isEmpty.value = false
    }
}

/**
 * @return { Promise }
 * @description 获取课程目录
 */
const initCourseCatalogue = async (): Promise<void> => {
    try {
        isnoBuy.value = false
        const res = await apiCourseCatalogue({
            id: cateId.value
        })
        courseData.value = res
        await apiCompletedStudy({
            courseId: courseId.value,
            catalogueId: cateId.value
        })
    } catch (err: any) {
        isnoBuy.value = true
        console.log(err)
    }
}

/**
 * @param { event } 当前点击的目录数据
 * @description 获取课程目录
 */
const handleRefresh = async (event: any) => {
    activeCourse.value = event
    if (event.id == cateId.value) return
    courseId.value = event.courseId
    cateId.value = event.id
    uni.showLoading({ title: '正在加载..' })
    // 请求目录
    try {
        await initCourseCatalogue()
        await initCourseDetail()

        uni.hideLoading()
        // 切换课程回到顶部
        uni.pageScrollTo({
            scrollTop: 0,
            duration: 100
        })
    } catch (error) {
        return
    }
}

//目录节流
const refleshThrottle = throttle(handleRefresh, 2000)

/**
 * @param { number } goodsNum
 * @return { void }
 * @description 处理下单
 */
const handleOrder = async (): Promise<void> => {
    if (!isLogin.value) return goPage('/pages/login/index')
    try {
        const { order_id, type } = await apiPlaceOrder({
            course_id: courseId.value
        })
        const params = {
            order_id,
            from: type
        }
        goPage(`/pages/order_buy/index?params=${JSON.stringify(params)}`)
    } catch (err) {
        //TODO handle the exception
        throw new Error(err + '订单下单报错')
    }
}
/**

 * @description 返回购买
 */
const backToBuy = () => {
    uni.navigateBack()
}

/**
 * @param { string } url
 * @return { void }
 * @description 跳转页面方法
 */
const goPage = (url: string) => {
    uni.navigateTo({
        url: url
    })
}

//页面被点击
const pageClick = () => {
    TWcateHide.value = false
}

/** Methods End **/

onPageScroll(({ scrollTop }: any) => {
    if (type.value == 1) {
        TWcateHide.value = true
        // TWdebounce()
        const top = uni.upx2px(100)
        BGpercent.value = scrollTop / top > 1 ? 1 : scrollTop / top
    }
})

/** Life Cycle Start **/
onLoad((options: any) => {
    type.value = options.type
    //图文修改导航栏背景
    type.value != 1 ? (BGpercent.value = 1) : ''
    cateId.value = options.cate_id
    courseId.value = options.course_id
    initCourseId.value = options.course_id
})

onShow(() => {
    initCourseDetail()
    initCourseCatalogue()
})
/** Life Cycle End **/
</script>

<style lang="scss">
.safeArea {
    padding-bottom: calc(env(safe-area-inset-bottom));
}

.study-course {
    // margin-bottom: 400rpx;
    // height: calc(100vh - env(safe-area-inset-bottom));
    // padding-bottom: calc(env(safe-area-inset-bottom));
    // 课程信息
    .course {
        .audio-wrapper {
            // padding: 24rpx;
            // height: 400rpx;
            // padding: 140rpx 0;
            // background-color: $color-white;
            ::v-deep .wx-slider-handle-wrapper {
                height: 10rpx !important;
                border: 16rpx !important;
                background: #b1cfff !important;
            }

            ::v-deep .wx-slider-track {
                background-color: $color-primary !important;
            }
        }

        .video-wrapper {
            // position: relative;
            // video {
            //     width: 100%;
            //     height: 400rpx;
            //     position: fixed;
            //     top: 0;
            //     z-index: 10;
            // }
        }

        .course-info {
            padding: 30rpx;
        }
    }
}

// 服务下架或不存在时
.empty {
    padding-top: 200rpx;

    .empty-bottom {
        width: 90vw;
        margin-top: 130rpx;
    }
}

// 通用弹窗
.course-pop {
    width: 640rpx;
    padding: 70rpx 80rpx 40rpx 80rpx;
}
</style>
